package api

import (
	"TaskAssignmentSystem/internal/admin/dao"
	adminServices "TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/app/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"github.com/kataras/iris/v12"
)

type AdvListRequest struct {
	Page     int64 `json:"page"`
	PageSize int64 `json:"page_size"`
}

func AdvListHandler(ctx iris.Context) {
	var RequestParams AdvListRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var advServe services.CommonService[dao.SystemAdv]
	advServe.Page = RequestParams.Page
	advServe.PageSize = RequestParams.PageSize
	advServe.Order = "sort"
	advServe.Query = map[string]interface{}{"status": dao.AdvOnlineStatus}
	if res, err := advServe.SelectList(); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": res.Total, "list": res.Data}))
		return
	}

}

type AdvClickRequest struct {
	AdvId uint `json:"adv_id" validate:"required"`
}

func AdvClickCodeHandler(ctx iris.Context) {
	var RequestParams AdvClickRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	}
	var advServe adminServices.SystemAdvService
	if _, err := advServe.AdvFindById(RequestParams.AdvId); err != nil {
		ctx.JSON(utils.ResponseServerError(errors.New("该广告不存在")))
		return
	}
	var serve services.SystemAdvService
	if err := serve.AdvClick(RequestParams.AdvId, claims.Id); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}
